package com.xindacloud.sms.adapter.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindacloud.sms.adapter.dao.SmsAccountTransationMapper;
import com.xindacloud.sms.adapter.dao.SmsUserMapper;
import com.xindacloud.sms.adapter.entity.SmsAccountTransation;
import com.xindacloud.sms.adapter.entity.SmsUser;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsUserService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import com.xindacloud.sms.adapter.vo.UserRoleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;


@Slf4j
@Service
public class SmsUserServiceImpl extends ServiceImpl<SmsUserMapper, SmsUser> implements ISmsUserService {

    final SmsUserMapper userMapper;

    final SmsAccountTransationMapper accountTransationMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public SmsUserServiceImpl(SmsUserMapper userMapper, SmsAccountTransationMapper accountTransationMapper) {
        this.userMapper = userMapper;
        this.accountTransationMapper = accountTransationMapper;
    }

    @Override
    public SmsUser queryUserInfoById(Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper(SmsUser.builder().userId(userId).build());
        return getOne(queryWrapper);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSmsPrice(Integer userId, BigDecimal sumSmsPrice) {
        Optional.of(userId)
                .orElseThrow(() -> new ServiceException("userId不能为空.", UnionResultHelp.StatusEnum.ParamsFail.code()));
        BigDecimal balance = queryUserInfoById(userId).getBalance();
        accountTransationMapper.insert(SmsAccountTransation.builder()
                .accountUserId(userId)
                .operatorId(userId)
                .transationAction("-")
                .transationId(UUID.randomUUID().toString().replaceAll("-", ""))
                .transationPrice(String.valueOf(sumSmsPrice))
                .build());
        //余额不足
        if (balance.compareTo(sumSmsPrice) < 0) {
            throw new ServiceException("账户余额不足.", UnionResultHelp.StatusEnum.BadRequest.code());
        }
        if (sumSmsPrice.doubleValue() > 0) {
            BigDecimal subtractValue = balance.subtract(sumSmsPrice);
            UpdateWrapper<SmsUser> updateWrapper = new UpdateWrapper<>(SmsUser.builder()
                    .userId(userId)
                    .build())
                    .set("balance", subtractValue);
            return update(updateWrapper);
        }
        return false;
    }

    @Override
    public SmsUser queryUserInfoFor(String username, String password) {

        return lambdaQuery()
                .eq(SmsUser::getStatus, false)
                .eq(StringUtils.isNotEmpty(username), SmsUser::getUsername, username)
                .eq(StringUtils.isNotEmpty(password), SmsUser::getPassword, password)
                .one();

    }

    @Override
    public List<UserRoleVO> queryUserRoleList(Integer userId) {
        return userMapper.queryUserRoleList(userId);
    }

    @Override
    public List<SmsUser> queryUserInfoListByParentUserId(Integer userId) {
        return lambdaQuery()
                .eq(SmsUser::getParentUserId, userId)
                .list();
    }
}
